package com.ds.infra.rpc.core.transport.server;

import com.ds.infra.rpc.core.protocol.RpcRequest;
import com.ds.infra.rpc.core.protocol.RpcResponse;
import com.ds.infra.rpc.core.transport.codec.RpcDecoder;
import com.ds.infra.rpc.core.transport.codec.RpcEncoder;
import com.ds.infra.rpc.core.transport.server.handler.RpcRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;

/**
 * Netty服务端核心实现
 *
 * @author WeiShaoying
 */
@Slf4j
public class NettyServer implements RpcServer, DisposableBean {

    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private final int port;
    private Channel channel;

    public NettyServer(int port) {
        this.port = port;
        this.bossGroup = new NioEventLoopGroup(1);
        this.workerGroup = new NioEventLoopGroup();
    }

    @Override
    public void start() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline()
                                    .addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 4, 4,0,0))
                                    .addLast(new RpcDecoder<>(RpcRequest.class))  // 指定请求类型
                                    .addLast(new RpcEncoder<>(RpcResponse.class)) // 指定响应类型
                                    .addLast(new RpcRequestHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.TCP_NODELAY, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            channel = future.channel();
            log.info("========= RPC server started on port {}", port);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Server startup interrupted", e);
        }
    }

    @Override
    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        log.info("==== RPC server shutdown");
    }

    @Override
    public void destroy() {
        shutdown();
    }
}
